package com.module.user.ui.downCloudData

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.common.app.utls.SseManager
import com.common.base.app.viewmodel.BaseViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/07/25
 * <p>
 * 描述：下载云端数据VM
 * <p>
 * 修订历史：
 */
class DownCloudDataViewModel : BaseViewModel() {

    private val sseManager = SseManager()

    val _sseData = MutableLiveData<String>()

    init {
        // 在IO线程监听SSE事件，在Main线程更新UI
        viewModelScope.launch {
            sseManager.sseEvents
                // SSE处理在IO线程
                .collect { event ->
                    // collect在Main线程执行，可以安全更新UI
                    when (event) {
                        is SseManager.SseEvent.Data -> {
                            _sseData.value = event.content
                        }
                        is SseManager.SseEvent.Error -> {
                            Log.e("SSE", "Error: ${event.message}")
                        }
                        is SseManager.SseEvent.Connected -> {
                            Log.d("SSE", "Connected")
                        }
                        is SseManager.SseEvent.Disconnected -> {
                            Log.d("SSE", "Disconnected")
                        }
                    }
                }
        }
    }

    fun startSse() {
        sseManager.startSseConnection(viewModelScope)
    }

    /**
     * 重新连接SSE
     */
    fun reconnectSse() {
        sseManager.stopSseConnection()
        sseManager.startSseConnection(viewModelScope)
    }

    /**
     * 带延迟的重连（避免频繁重连）
     */
    fun reconnectSseWithDelay(delayMs: Long = 1000) {
        viewModelScope.launch {
            sseManager.stopSseConnection()
            delay(delayMs)
            sseManager.startSseConnection(viewModelScope)
        }
    }

    fun stopSse() {
        sseManager.stopSseConnection()
    }

    override fun onCleared() {
        super.onCleared()
        sseManager.stopSseConnection()
    }
}